package com.xww.common.exception;


import com.xww.common.base.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@ControllerAdvice
@Component
public class CommonExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResultData handle(Exception exception) {
        if(exception instanceof CommonException){
            LOGGER.error(exception.getMessage(),exception);
            CommonException e = (CommonException) exception;
            LOGGER.error("捕获到异常,异常代码为{},异常信息为{}",e.getErrCode(),e.getErrMsg());
            exception.printStackTrace();
            return ResultData.fail(e.getErrCode(),e.getErrMsg());
        }else if(exception instanceof HttpMessageNotReadableException){
            LOGGER.error("前台传入JSON格式错误");
            exception.printStackTrace();
            return ResultData.fail(CommonError.PARAMETER_JSONFORMAT_ERROR);
        }else{
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            LOGGER.error("捕获到异常错误");
            exception.printStackTrace();
            exception.printStackTrace(new PrintStream(baos));
            String exception1 = baos.toString();
            LOGGER.error("baos:-----" + exception1);
            return ResultData.fail(CommonError.UNKOWN_ERROR);
        }
    }
}
